import { Gird } from "./Gird";
import Main from "./Main";


export class Search {

    private _gird: Gird = null;
    private openList: cc.Vec2[] = [];
    private closeList: cc.Vec2[] = [];
    private _main: Main = null;

    public startpos: cc.Vec2 = null;

    constructor( game: Main ){
        this._main = game;
        this._gird = this._main.Gird;
    }

    /** 单步寻路 */
    public stepfindpath ( complete?: Function ){

        let nearList = this._gird.getPosNearFourPosNum(this.startpos);
        this.openList = this.openList.concat(nearList);
        for( let i = 0; i < this.openList.length; i++){                            //去除已经走过的位置
            
            let index = this._gird.getblockArrayIndex(this.openList[i]);
            let openindexList = this._gird.getIndexArray(this.closeList);
            if( openindexList.indexOf( index ) > -1 ){
                this.openList.splice( i, 1);
                i--;
            }
        }
        let endBlock = this._gird.endBlock;
        this.openList.sort((a, b)=>{

            let pointa_f = Math.abs(endBlock.x - a.x) + Math.abs(endBlock.y - a.y);
            let pointb_f = Math.abs(endBlock.x - b.x) + Math.abs(endBlock.y - b.y);
            if(pointa_f < pointb_f){
                return -1;
            }else if( pointb_f == pointb_f){
                
                return 0;
            }else{
                return 1;
            }
        });
        
        for( let i = 0; i < this.openList.length; i++){
            if(this.openList[i].x == endBlock.x && this.openList[i].y == endBlock.y){
                cc.log("已经找到位置");
                return;
            }
        }

        let first = this.openList.shift();   //取最短的
        this.startpos = first;
        this.closeList.push(this.startpos);
        cc.log("当前找到的位置", this.startpos);
        this._gird.setHasFindpos(first);
        complete && complete();
    }

}